package com.ruoyi.web.controller.deepSeek;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * deepSeek
 * 三方
 */
@RestController
@RequestMapping("/api/deepseek")
public class DeepSeekAIController {

    private final WebClient webClient;
    private static final Logger logger = LoggerFactory.getLogger(DeepSeekAIController.class);

    @Value("${siliconflow.api.key}") // 从配置文件获取 API Key
    private String apiKey;

    public DeepSeekAIController(WebClient.Builder webClientBuilder) {
        // 配置 WebClient，设置基础 URL 和超时
        this.webClient = webClientBuilder
                .baseUrl("https://api.siliconflow.cn/v1")
                .build();
    }

    @PostMapping("/chat")
    public Mono<String> chatWithAI(@RequestBody Map<String, Object> userRequest) {
        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-ai/DeepSeek-V3"); // 选择 DeepSeek 模型
        requestBody.put("messages", userRequest.get("messages"));
        requestBody.put("stream", false);
        requestBody.put("max_tokens", 512);
        requestBody.put("temperature", 0.7);
        requestBody.put("top_p", 0.7);
        requestBody.put("top_k", 50);
        requestBody.put("frequency_penalty", 0.5);
        requestBody.put("n", 1);

        Map<String, String> responseFormat = new HashMap<>();
        responseFormat.put("type", "text");
        requestBody.put("response_format", responseFormat);

        // 打印请求体日志（可选，方便调试）
        logger.info("发送请求到 DeepSeek API，请求体：{}", requestBody);

        // 发送请求到 DeepSeek API，设置超时和错误处理
        return webClient.post()
                .uri("/chat/completions")
                .header(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
                .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .bodyValue(requestBody)
                .retrieve()
                .bodyToMono(String.class)
                .timeout(Duration.ofSeconds(30))  // 设置超时时间（例如30秒）
                .doOnError(error -> logger.error("请求 DeepSeek API 失败：{}", error.getMessage()))  // 错误时记录日志
                .onErrorResume(e -> Mono.just("错误： " + e.getMessage())); // 错误时返回一个默认的错误信息
    }
}
